import { serialize } from "@/utils/utils"
import axios from "axios"
import { MessageBox, Message } from "element-ui"
import store from "@/store"
import { getToken } from "@/utils/auth"

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // 跨域请求时发送Cookie
  timeout: 6000 // 请求超时
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const isToken = (config.headers || {}).isToken === false

    // 在发送请求之前做一些事情
    let token = store.getters.access_token
    // console.log(store.getters)
    // console.log(token)
    if (token) {
      // 让每个请求都带有令牌
      config.headers["Authorization"] = "Bearer " + token
    }
    // headers中配置serialize为true开启序列化
    if (config.methods === "post" && config.headers.serialize) {
      config.data = serialize(config.data)
      delete config.data.serialize
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    const statusCode = response.status

    if (statusCode !== 200) {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 2 * 1000
      })
      return Promise.reject(new Error(res.message || "Error"))
    } else {
      return res
    }
  },
  error => {
    console.log(error)
    console.log("err" + error)
    Message({
      message: error.message,
      type: "error",
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
